/**
 * 
 */
package vn.lumi.smarthome.ui;

import vn.lumi.smarthome.Config;
import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.network.NetMessage;
import vn.lumi.smarthome.service.SmartHomeService;
import vn.lumi.smarthome.service.VibrateThread;
import vn.lumi.smarthome.ulti.Preference;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;

import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;

/**
 * @author hieu
 * 
 */
public class SettingActivity extends SherlockFragmentActivity implements
		ServiceConnection {
	// private static final int STATUS = 1;
	private static final int PROGRESS_DIALOG_ID = 2;

	public static final int LANGUAGE_AUTO = 1;
	public static final int LANGUAGE_VIETNAM = 2;
	public static final int LANGUAGE_ENGLISH = 3;

	CountDownTimer mTimer = null;

	// private boolean stateActivity = false;

	private ServiceConnection mConnection = (ServiceConnection) this;
	private Messenger mServiceMessenger = null;

	boolean mIsBound;
	BroadcastReceiver mReceiver;
	// End
	String pwd;
	EditText currenPwd, newPwd, confirmPwd, account;
	TextView logOut, txtSeting;
	Button ok;

	private ExpandableListView mExpandableListView;
	private ExpandableListAdapterSetting expandleAdapter;

	// MenuItem setting,logOut;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		Config.configLanguage(getBaseContext(),
				Preference.getLanguage(getApplicationContext()));// Thiet lap
																	// ngon ngu
		setContentView(R.layout.activity_setting);

		setupActionBar();
		// BroastcastReceiver
		IntentFilter filter = new IntentFilter("ackMessageChangePwd");
		mReceiver = new PassWordReceive();
		registerReceiver(mReceiver, filter);
		//

		mExpandableListView = (ExpandableListView) findViewById(R.id.fragment_setting_expand_listview);
		expandleAdapter = new ExpandableListAdapterSetting(
				getApplicationContext());
		mExpandableListView.setAdapter(expandleAdapter);
		mExpandableListView
				.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

					@Override
					public boolean onGroupClick(ExpandableListView parent,
							View v, int groupPosition, long id) {
						// TODO Auto-generated method stub
						if (Config.isVibrate)
							new VibrateThread(getApplicationContext()).start();
						return false;
					}
				});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Config.isVibrate = Preference.getVibrate(this);
		// Config.configLanguage(getBaseContext(),
		// Preference.getLanguage(getApplicationContext()));// Thiet lap
		// // ngon ngu
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		doBindService();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		doUnbindService();

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
	}

	private void changeLanguage() {
		Config.configLanguage(getBaseContext(),
				Preference.getLanguage(getApplicationContext()));// Thiet lap
																	// ngon ngu
		mExpandableListView.setAdapter(expandleAdapter);
		txtSeting.setText(R.string.txt_setting);
		logOut.setText(R.string.txt_logout);
	}

	private void setupActionBar() {
		ActionBar actionbar = getSupportActionBar();
		actionbar.setCustomView(R.layout.actionbar_setting_activity);
		actionbar.setDisplayShowHomeEnabled(false);
		actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionbar.setDisplayShowHomeEnabled(false);
		actionbar.setDisplayShowTitleEnabled(false);
		logOut = (TextView) findViewById(R.id.actionbar_setting_activity_logout);
		logOut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Config.isVibrate)
					new VibrateThread(getApplicationContext()).start();
				showDialog(getString(R.string.txt_Announcement),
						getString(R.string.txt_Announcement_exit));
			}
		});
		txtSeting = (TextView) findViewById(R.id.actionbar_setting_activity_set);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		try {
			unregisterReceiver(mReceiver);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void doBindService() {
		if (SmartHomeService.isRunning()) {
			bindService(new Intent(getApplicationContext(),
					SmartHomeService.class), mConnection,
					Context.BIND_AUTO_CREATE);

		}
	}

	private void doUnbindService() {
		if (mIsBound) {
			// If we have received the service, and hence registered with it,
			// then now is the time to unregister.

			// Detach our existing connection.
			unbindService(mConnection);
			Log.d("CP", "Unbinding from Service");
		}
	}

	public class ExpandableListAdapterSetting extends BaseExpandableListAdapter {

		public final static int TYPE_CHANGE_PWD = 0;
		public final static int TYPE_VIBRATE = 1;
		public final static int TYPE_LANGUAGE = 3;
		public final static int TYPE_ABOUT = 4;
		public final static int TYPE_CAUTION_PR = 2;

		private Context mContext;

		public ExpandableListAdapterSetting(Context mContext) {
			this.mContext = mContext;

		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			LayoutInflater infalInflater = (LayoutInflater) mContext
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			switch (groupPosition) {
			case TYPE_CHANGE_PWD:
				convertView = infalInflater.inflate(
						R.layout.activity_dialog_pwd, null);
				ok = (Button) convertView
						.findViewById(R.id.activity_dialog_pwd_btn_ok);
				ok.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (Config.isVibrate)
							new VibrateThread(getApplicationContext()).start();
						String curPwd = currenPwd.getText().toString();
						String nwPwd = newPwd.getText().toString();
						String cfirmPwd = confirmPwd.getText().toString();
						// TODO Auto-generated method stub
						if (!curPwd.equals("") && !nwPwd.equals("")
								&& !cfirmPwd.equals("")) {
							if (curPwd.equals(LumiHome.password)) {
								if (nwPwd.equals(cfirmPwd)) {
									showDialog(PROGRESS_DIALOG_ID);
									Log.e("test", "dialog");
									sendMessageToService(
											NetMessage.CMD_APP_CHANGE_PASSWORD,
											newPwd.getText().toString());
									pwd = nwPwd;
								} else {
									showDialog(getString(R.string.txt_error_invalid_confirm_user_pwd));
								}
							} else {
								showDialog(getString(R.string.txt_error_invalid_enter_pwd));
							}
						} else {
							showDialog(getString(R.string.txt_error_invalid_enter_fully));
						}
					}
				});
				currenPwd = (EditText) convertView
						.findViewById(R.id.activity_dialog_pwd_current_pwd);
				newPwd = (EditText) convertView
						.findViewById(R.id.activity_dialog_pwd_new_pwd);
				confirmPwd = (EditText) convertView
						.findViewById(R.id.activity_dialog_pwd_confirm_pwd);
				account = (EditText) convertView
						.findViewById(R.id.activity_dialog_pwd_username);
				account.setText(Preference.getUID(getApplicationContext()));
				break;
			case TYPE_VIBRATE:
				convertView = infalInflater.inflate(
						R.layout.item_expandablelistview_vibrate, null);
				RadioGroup rbg_vibrate = (RadioGroup) convertView
						.findViewById(R.id.rbg_vibrate);
				RadioButton rbg_vibrate_on = (RadioButton) convertView
						.findViewById(R.id.rbg_vibrate_on);
				RadioButton rbg_vibrate_off = (RadioButton) convertView
						.findViewById(R.id.rbg_vibrate_off);
				// RadioButton rbg_vibrate_on =
				// (RadioButton)convertView.findViewById(R.id.rbg_vibrate_on);
				// RadioButton rbg_vibrate_off =
				// (RadioButton)convertView.findViewById(R.id.rbg_vibrate_off);
				if (Preference.getVibrate(getApplicationContext()))
					rbg_vibrate_on.setChecked(true);
				else {
					rbg_vibrate_off.setChecked(true);
				}
				rbg_vibrate
						.setOnCheckedChangeListener(new OnCheckedChangeListener() {

							@Override
							public void onCheckedChanged(RadioGroup group,
									int checkedId) {
								// TODO Auto-generated method stub
								if (Config.isVibrate)
									new VibrateThread(getApplicationContext())
											.start();
								switch (checkedId) {
								case R.id.rbg_vibrate_on:
									Preference.saveVibrate(mContext, true);
									break;
								case R.id.rbg_vibrate_off:
									Preference.saveVibrate(mContext, false);
									break;
								default:
									break;
								}
							}
						});
				break;
			case TYPE_ABOUT:
				convertView = infalInflater.inflate(
						R.layout.activity_about_lumihome, null);

				break;
			case TYPE_CAUTION_PR:
				convertView = infalInflater.inflate(
						R.layout.item_expandablelistview_vibrate, null);
				RadioGroup rbg_vibrate_pr = (RadioGroup) convertView
						.findViewById(R.id.rbg_vibrate);
				RadioButton rbg_vibrate_on_pr = (RadioButton) convertView
						.findViewById(R.id.rbg_vibrate_on);
				RadioButton rbg_vibrate_off_pr = (RadioButton) convertView
						.findViewById(R.id.rbg_vibrate_off);
				if (Preference.getVibratePr(getApplicationContext()))
					rbg_vibrate_on_pr.setChecked(true);
				else {
					rbg_vibrate_off_pr.setChecked(true);
				}
				rbg_vibrate_pr
						.setOnCheckedChangeListener(new OnCheckedChangeListener() {

							@Override
							public void onCheckedChanged(RadioGroup group,
									int checkedId) {
								// TODO Auto-generated method stub
								if (Config.isVibrate)
									new VibrateThread(getApplicationContext())
											.start();
								switch (checkedId) {
								case R.id.rbg_vibrate_on:
									Preference.saveVibratePr(mContext, true);
									Config.isVibrate = Preference
											.getVibrate(mContext);
									break;
								case R.id.rbg_vibrate_off:
									Preference.saveVibratePr(mContext, false);
									Config.isVibrate = Preference
											.getVibrate(mContext);
									break;
								default:
									break;
								}
							}
						});
				break;
			case TYPE_LANGUAGE:
				convertView = infalInflater.inflate(
						R.layout.item_expandablelistview_multilanguage, null);
				RadioGroup rbg_language = (RadioGroup) convertView
						.findViewById(R.id.rbg_multilgg);
				final RadioButtonCustom rbg_vi = (RadioButtonCustom) convertView
						.findViewById(R.id.rbg_multilgg_vi);
				final RadioButtonCustom rbg_en = (RadioButtonCustom) convertView
						.findViewById(R.id.rbg_multilgg_en);
				if (Preference.getLanguage(getApplicationContext()) == LANGUAGE_VIETNAM) {
					rbg_vi.setChecked(true);
				} else if (Preference.getLanguage(getApplicationContext()) == LANGUAGE_ENGLISH)
					rbg_en.setChecked(true);

				rbg_vi.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Preference.saveLanguage(getApplicationContext(),
								LANGUAGE_VIETNAM);
						changeLanguage();
					}
				});
				rbg_en.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Preference.saveLanguage(getApplicationContext(),
								LANGUAGE_ENGLISH);
						changeLanguage();
					}
				});

				break;

			}
			return convertView;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			// TODO Auto-generated method stub
			return 1;
		}

		@Override
		public Object getGroup(int groupPosition) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public int getGroupCount() {
			// TODO Auto-generated method stub
			return 5;
		}

		@Override
		public long getGroupId(int groupPosition) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			if (convertView == null) {
				LayoutInflater infalInflater = (LayoutInflater) mContext
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = infalInflater
						.inflate(
								vn.lumi.smarthome.R.layout.item_expandablelistview_groupview,
								null);
			}
			TextViewCustom titleGroup = (TextViewCustom) convertView
					.findViewById(vn.lumi.smarthome.R.id.item_expandablelistview_groupview_txt);
			switch (groupPosition) {
			case TYPE_CHANGE_PWD:
				titleGroup
						.setText(getString(R.string.activity_setting_groupView_change_pwd));
				titleGroup.setTextColor(mContext.getResources().getColor(
						R.color.greenLight));
				break;
			case TYPE_VIBRATE:
				titleGroup
						.setText(getString(R.string.activity_setting_groupView_VIBRATE));
				titleGroup.setTextColor(mContext.getResources().getColor(
						R.color.greenLight));
				break;
			case TYPE_CAUTION_PR:
				titleGroup
						.setText(getString(R.string.activity_setting_groupView_PIR));
				titleGroup.setTextColor(mContext.getResources().getColor(
						R.color.greenLight));
				break;

			case TYPE_LANGUAGE:
				titleGroup
						.setText(R.string.activity_setting_title_groupView_language);
				titleGroup.setTextColor(mContext.getResources().getColor(
						R.color.greenLight));
				break;

			case TYPE_ABOUT:
				titleGroup
						.setText(getString(R.string.activity_setting_groupView_ABOUT));
				titleGroup.setTextColor(mContext.getResources().getColor(
						R.color.greenLight));
				break;
			}
			return convertView;
		}

		@Override
		public boolean hasStableIds() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return false;
		}

	}

	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub

		switch (id) {
		case PROGRESS_DIALOG_ID: {
			ProgressDialog mDialogProgress = new ProgressDialog(this);
			mDialogProgress
					.setMessage(getString(R.string.activity_setting_Password_is_changing));
			mDialogProgress.setCancelable(true);
			mDialogProgress.show();
			// Thay doi font chu cua Dialog
			ChangeFont changeFont = new ChangeFont(getApplicationContext());
			TextView textView = (TextView) mDialogProgress
					.findViewById(android.R.id.message);
			textView = changeFont.changeFontTextView(textView,
					getString(R.string.activity_setting_Password_is_changing),
					LumiHome.font, 16, Gravity.NO_GRAVITY, getResources()
							.getColor(R.color.white));
			return mDialogProgress;
		}
		}
		return null;
	}

	private void showDialog(String msg) {
		AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
				new ContextThemeWrapper(this, R.style.AlertDialogCustom));
		// ErrorDialog.setTitle("Lỗi");
		ChangeFont changeFont = new ChangeFont(getApplicationContext());
		TextView tvErrorDialog = new TextView(getApplicationContext());
		tvErrorDialog = changeFont.changeFontTextView(tvErrorDialog, "Lỗi",
				LumiHome.fontBold, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		ErrorDialog.setCustomTitle(tvErrorDialog);
		ErrorDialog.setMessage(msg);
		ErrorDialog.setNegativeButton("OK",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (Config.isVibrate)
							new VibrateThread(getApplicationContext()).start();
						dialog.cancel();
					}
				});
		AlertDialog alertErrorDialog = ErrorDialog.create();
		alertErrorDialog.show();
		TextView textView = (TextView) alertErrorDialog
				.findViewById(android.R.id.message);
		textView = changeFont.changeFontTextView(textView, msg, LumiHome.font,
				LumiHome.sizeContent, Gravity.NO_GRAVITY, getResources()
						.getColor(R.color.greenActionbar));

		Button btn1 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_NEGATIVE);
		btn1.setTypeface(Typeface.createFromAsset(getAssets(), LumiHome.font));
		btn1.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn1.setTextSize(LumiHome.sizeButton);
	}

	private void showDialog(String title, String msg) {
		AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
				new ContextThemeWrapper(this, R.style.AlertDialogCustom));
		ChangeFont changeFont = new ChangeFont(getApplicationContext());
		TextView tvErrorDialog = new TextView(getApplicationContext());
		tvErrorDialog = changeFont.changeFontTextView(tvErrorDialog, title,
				LumiHome.fontBold, LumiHome.sizeTittle, Gravity.CENTER,
				getResources().getColor(R.color.green));
		ErrorDialog.setCustomTitle(tvErrorDialog);
		ErrorDialog.setMessage(msg);
		ErrorDialog.setNegativeButton("OK",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (Config.isVibrate)
							new VibrateThread(getApplicationContext()).start();
						Preference.saveUID(getApplicationContext(), "");
						Preference.savepwd(getApplicationContext(), "");
						Intent intent = new Intent(getApplicationContext(),
								MainActivity.class);
						intent.putExtra("finish", true);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
						finish();
					}
				});
		ErrorDialog.setPositiveButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if (Config.isVibrate)
							new VibrateThread(getApplicationContext()).start();
						dialog.cancel();
					}
				});
		AlertDialog alertErrorDialog = ErrorDialog.create();
		alertErrorDialog.show();
		TextView textView = (TextView) alertErrorDialog
				.findViewById(android.R.id.message);
		textView = changeFont.changeFontTextView(textView, msg, LumiHome.font,
				LumiHome.sizeContent, Gravity.NO_GRAVITY, getResources()
						.getColor(R.color.greenActionbar));

		Button btn1 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_NEGATIVE);
		btn1.setTypeface(Typeface.createFromAsset(getAssets(), LumiHome.font));
		btn1.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn1.setTextSize(LumiHome.sizeButton);
		Button btn2 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_POSITIVE);
		btn2.setTypeface(Typeface.createFromAsset(getAssets(), LumiHome.font));
		btn2.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn2.setTextSize(LumiHome.sizeButton);
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		if (Config.isVibrate)
			new VibrateThread(getApplicationContext()).start();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.content.ServiceConnection#onServiceConnected(android.content.
	 * ComponentName, android.os.IBinder)
	 */
	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		// TODO Auto-generated method stub
		mIsBound = true;
		mServiceMessenger = new Messenger(service);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.content.ServiceConnection#onServiceDisconnected(android.content
	 * .ComponentName)
	 */
	@Override
	public void onServiceDisconnected(ComponentName name) {
		// TODO Auto-generated method stub
		mIsBound = false;
		mServiceMessenger = null;
	}

	private void sendMessageToService(int MsgType, String pass) {
		if (mIsBound) {
			if (mServiceMessenger != null) {
				try {
					Message msg = Message.obtain(null,
							SmartHomeService.UI2SER_NEW_MSG);
					Bundle b = new Bundle();
					b.putInt("Message Type", MsgType);
					// b.putParcelable("ContentProvider Message", appMsg);
					b.putString("PassWord", pass);
					msg.setData(b);
					// msg.replyTo = mMessenger;
					mServiceMessenger.send(msg);
				} catch (RemoteException e) {
				}
			}
		}
	}

	public class PassWordReceive extends BroadcastReceiver {

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * android.content.BroadcastReceiver#onReceive(android.content.Context,
		 * android.content.Intent)
		 */
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			removeDialog(PROGRESS_DIALOG_ID);
			showDialog(getString(R.string.activity_setting_Password_is_changed_susscesfull));
			LumiHome.password = pwd;

		}

	}

}
